package com.apply.service;

import com.apply.config.EmailManager;
import com.apply.config.Md5Utils;
import com.apply.entity.ApplyInfo;
import com.apply.entity.SysUser;
import com.apply.repository.ApplyRepository;
import com.apply.repository.UserRepository;
import com.apply.repository.spec.ApplyInfoRepositorySpec;
import com.apply.repository.spec.UserRepositorySpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tianp
 */
@Service
public class UserService {
    @Resource
    private UserRepository userRepository;
    @Autowired
    private EmailManager emailManager;
    @Autowired
    private AuthService authService;
    @Autowired
    private ApplyRepository applyRepository;

    public SysUser login(SysUser sysUser, Integer roleId) {
        SysUser byUsername = userRepository.findByUsernameAndRoleId(sysUser.getUsername(), roleId);
        if (Md5Utils.getMD5(sysUser.getPassword()).equals(byUsername.getPassword())) {
            return byUsername;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(String username, String password) {
        int flag = userRepository.updatePassowrd(Md5Utils.getMD5(password), username);
        return flag > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public SysUser insertUser(SysUser sysUser, Integer roleId) {
        SysUser byUsername = userRepository.findByUsernameAndRoleId(sysUser.getPassword(), roleId);
        if (null != byUsername) {
            return null;
        }
        sysUser.setPassword(Md5Utils.getMD5(sysUser.getPassword()));
        //普通用户
        sysUser.setRoleId(roleId);
        return userRepository.save(sysUser);
    }

    public Page<SysUser> findAllByPage(int pageNum, int pageSize) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Page<SysUser> list = userRepository.findAll(new PageRequest(pageNum, pageSize, sort));
        return list;
    }

    public void sendEmailCode(String code, String address) {
        List<String> list = new ArrayList<>();
        //tianpeng@365ime.com
        list.add(address);
        String subject = "邮箱验证";
        String content = "<h1>用户您好，您的验证码是:</h1>" + code;
        emailManager.sendEmail(list, subject, content, null, null);
    }

    public SysUser getOne(Long id) {
        return userRepository.findOne(id);
    }

    public void logout(HttpServletRequest request) {
        request.getSession(false).removeAttribute("user");
    }

    public Page<SysUser> querySysUser(SysUser sysUser, Integer pageNum) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        return userRepository.findAll(UserRepositorySpec.getSpec(sysUser.getRealname(), sysUser.getUsername(), sysUser.getSex()),
                new PageRequest(pageNum, 10, sort));
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSysUser(SysUser sysUser, String sid) {
        SysUser origin = userRepository.findOne(sysUser.getId());
        //真实姓名
        if (null != sysUser.getRealname()) {
            origin.setRealname(sysUser.getRealname());
        }
        //性别
        if (null != sysUser.getSex()) {
            origin.setSex(sysUser.getSex());
        }
        //身份证号
        if (null != sysUser.getIdcard()) {
            origin.setIdcard(sysUser.getIdcard());
        }
        //联系电话
        if (null != sysUser.getPhoneNum()) {
            origin.setPhoneNum(sysUser.getPhoneNum());
        }
        //修改成功之后需要清空缓存
        if (userRepository.save(origin) != null) {
            authService.remove(sid, origin);
            return true;
        }
        return false;
    }

    public Page<ApplyInfo> pageUserApplyInfo(ApplyInfo applyInfo, PageRequest pageRequest) {
        return applyRepository.findAll(ApplyInfoRepositorySpec.getSpec(applyInfo), pageRequest);
    }
}
